import json
import re

import requests

"""
从提供的URL接口中获取疫情数据
"""


def getData(UrlInter):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
    }

    comments = requests.get(UrlInter, headers=headers)
    code = comments.status_code  # URL获取情况状态代码
    cov_data = comments.text
    return cov_data


"""
对爬取的疫情非规范的json数据进行初步规范化
"""


def jsonZH(data):
    res_data = ''.join(
        re.findall(r'[(](.*?)[)]', data)) \
        .replace('\\', '') \
        .replace('"{"', '{"') \
        .replace('}"', '}').replace("'", '"')
    return res_data


"""
获取国内每日新增历史数据、国内每日历史数据、各省较上日各病历类型变化情况
"""


def chinaDayList():
    url_api = 'https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=chinaDayList,chinaDayAddList,nowConfirmStatis,provinceCompare'
    data_list = json.loads(getData(url_api))
    return data_list


"""
国内各省市截至目前情况，这些数据可用于前端显示
"""


def china_data():
    url_api = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery351041864166324316376_1616323824045&_=1616323824046'
    rs = json.loads(jsonZH(getData(url_api)))
    return rs


if __name__ == '__main__':
    """
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery351041864166324316376_1616323824045&_=1616323824046'
    temp0 = getData(url)
    temp1 = jsonZH(temp0)
    rs = json.loads(temp1)
    print(temp1)
    print('最近一次更新时间' + str(rs['data']['lastUpdateTime']))
    print('中国截止目前总体情况' + str(rs['data']['chinaTotal']))
    print('中国今日各类型病例较上日变化' + str(rs['data']['chinaAdd']))
    print('中国各省市情况（包括各省市截止目前为止的统计数据）' + str(rs['data']['areaTree'][0]['children']))
    """
    china_data()
